﻿package com.crl.core.config.section
{
	import com.crl.core.config.section.handler.IConfigSectionHandler;
	import com.crl.utils.StringUtil;
	
	import flash.system.ApplicationDomain;
	import flash.utils.Dictionary;
	import flash.utils.getQualifiedClassName;
	
	/**
	 * ...
	 * @author crl
	 */
	public class SectionManager
	{
		public var extenalSections:Dictionary;
		public var defaultSection:Dictionary;
		public function SectionManager() 
		{
			defaultSection = new Dictionary();
			defaultSection["appSettings"] = getQualifiedClassName(AppSetttingSection);
			defaultSection["connectionStrings"] = getQualifiedClassName(ConnectionStringSection);
		}
		
		public function getDomain():ApplicationDomain {
			return ApplicationDomain.currentDomain;
		}
		
		
		private function getSectionTypeClass(classFullName:String):Class {
			var domain:ApplicationDomain = getDomain();
			if (domain.hasDefinition(classFullName)==false) {
				return null;
			}
			return domain.getDefinition(classFullName) as Class;
		}
		
		public function getSection(sectionName:String,sectionNode:XML):Object {
			var type:String = defaultSection[sectionName];
			
			if (type==null) {
				type = extenalSections[sectionName];
			}
			
			var instance:*
			try {
				
				var cls:Class=getSectionTypeClass(type);
				instance = new cls();
				
			}catch(e:TypeError){
				
				throw new Error(StringUtil.substitute("{0}:{1} 类不存在",sectionName,type));
				
			}catch (e:Error) {
				
				throw new Error(StringUtil.substitute("{0}:{1} 节点配置不正确 :{2}",sectionName,type,e.message));
				
			}
			
			if (instance is IConfigSectionHandler) {
				
				return (instance as IConfigSectionHandler).create(sectionNode);
				
			}else if (instance is AbstractSection) {
				
				instance.deserializeSection(sectionNode);
				return instance.getRuntimeObejct();
				
			}else {
				
				throw new Error("定义的解析并不合适");
				
			}
			
			return null;
		}
		
	}
	
}